/**
 * Created by limeng on 16-4-24.
 */
delegateApp.controller('CreateProposalCtrl', function ($scope, $rootScope, $http) {
    $scope.proposal = {
        authorId : $rootScope.delegate.id,
        title : '',
        type : null,
        content : '',
        attachments : []
    };
    $scope.title = '创建提案';
    $scope.departmentList = [];

    $scope.saveAsDraft = function () {
        if ($scope.proposal.title == '') {
            bootbox.alert("请输入标题!");
            return;
        }
        $scope.proposal.state = 0;
        $scope.proposal.content = $('#textEditor')[0].innerHTML;

        $http.post('/proposal/', $scope.proposal)
            .success(function (data) {
                if (data.state == true) {
                    showAlert('保存成功', '提案成功保存至草稿箱!');
                } else {
                    showAlert('保存失败', '提案被服务器拒绝，错误提示为：\n' + data.result);
                }
            }).error(function () {
                showAlert('保存失败', '服务器没有响应请求！')
            });
    };

    $scope.publishProposal = function () {
        if ($scope.proposal.title == '') {
            bootbox.alert("请输入标题!");
            return;
        }
        $scope.proposal.state = 1;      //待审核
        $scope.proposal.content = $('#textEditor')[0].innerHTML;
        $http.post('/proposal/', $scope.proposal)
            .success(function (data) {
                if (data.state == true) {
                    bootbox.alert('发布成功, 提案已成功发布，请耐心等待主席团审核', function () {
                        history.go(-1);
                    });
                } else {
                    bootbox.alert('发布失败,提案被服务器拒绝，错误提示为：\n' + data.result);
                }
            }).error(function () {
                showAlert('发布失败', '服务器没有响应请求！')
            });
    };

    $scope.postAttachment = function ($flow) {
        var files = $flow.files;
        if (files.length == 0) {
            showAlert('上传附件', '没有任何附件被上传');
            return;
        }
        var fileArr = [];
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (file.progress() == 1 && !file.error) {
                var fileElement = {
                    filename : file.name,
                    size : file.size / 1024.0,
                    realName : file.uniqueIdentifier
                };
                fileArr.push(fileElement);
            }
        }
        $scope.proposal.attachments = fileArr;
    };
});